<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Db;
use think\Session;
use think\Cookie;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use app\index\controller\SendMsg;

class Login extends Controller
{
	private $redis;
	protected function _initialize()
	{
		$this->redis = new \Redis();
        $this->redis->connect('127.0.0.1', 6379);

	}
    public function telEmail($openid)
    {
        $this->assign('openid',$openid);
        return $this->fetch('login/telemail');
    }

    public function bindTelEmail()
    {

        if (Request::instance()->isAjax()){
            $data = input('post.');
            $newdata['user_tel'] = $data['tel'];
            $newdata['user_email'] = $data['email'];
            $newdata['user_openid'] = $data['openid'];
            $newdata['user_pwd'] = password_hash($data['pwd'],PASSWORD_DEFAULT); 
            $newdata['user_regtime'] = time();
            if(preg_match('/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/',$newdata['user_tel'])){
                 if(preg_match('/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',$newdata['user_email'])){
                       $row = Db::name('user')->field('user_tel,user_id')->where('user_tel',$newdata['user_tel'])->find();
                       if($row){
                            if(Db::name('user')->where('user_tel', $newdata['user_tel'])->update(['user_openid' => $newdata['user_openid'],'user_email'=>$newdata['user_email']])){
                                $regip = Request::instance()->ip();
                                $list = array(
                                    "uid" => $row['user_id'],
                                    "regip" => $regip
                                );
                                $ret = Db::name('usermore_information')->insertGetId($list);
                                if($ret){
                                    $result = ["code"=>1,"msg"=>"注册成功"];
                                }
                                // $result = ['code'=>1,'msg'=>'成功'];
                                Session::set('tel',$newdata['user_tel']);
                            }
                       }else{
                            if($uid = Db::name('user')->insertGetId($newdata)){
                                $regip = Request::instance()->ip();
                                $list = array(
                                    "uid" => $uid,
                                    "regip" => $regip
                                );
                                $ret = Db::name('usermore_information')->insertGetId($list);
                                if($ret){
                                    $result = ["code"=>1,"msg"=>"注册成功"];
                                }
                                // $result = ['code'=>1,'msg'=>'成功'];
                                 Session::set('tel',$newdata['user_tel']);
                            }else{
                                 $result = ['code'=>0,'msg'=>'此手机,已绑定'];
                            }
                       }
                 }else{
                    $result = ['code'=>0,'msg'=>'邮箱格式不正确'];
                 }
            }else{
                $result = ['code'=>0,'msg'=>'电话格式不正确'];
            }
        }else{
             $result = ['code'=>0,'msg'=>'非法操作'];
        }
        return json($result);
    }
    public function index()
    {
    	$rand = mt_rand(100,999);
    	$csrf_token  = password_hash($rand,PASSWORD_DEFAULT);
    	// $this->redis->connect('127.0.0.1', 6379);
    	$this->redis->set('csrftoken', $csrf_token);
    	$this->assign('token',$csrf_token);
        return $this->fetch('login/login');
    }

    //求职用户登录
    public function userLogin()
    {
    	if(Request::instance()->isPost()){
    		$data = input('post.');
    		if($this->redis->get('csrftoken')===$data['token']){
    			//查询数据库
    			$res = Db::name('user')->field('user_pwd')->where(["user_tel"=>$data['username'],'user_status'=>1])->find();
    			if($res){
    				//查到了用户 比较密码
					if (password_verify($data['pwd'],$res['user_pwd'])) { 
					    $arr = ['code'=>1,'msg'=>'登录成功'];
                        Session::set('tel',$data['username'].'用户');
                        Session::set('usercate',1);
                        if($data['save']=='save'){
                            Cookie::set('tel',$data['username'].'用户',['prefix'=>'job_','expire'=>3600*24*7]);                         
                        }
                        
					} else{
                        $arr = ['code'=>0,'msg'=>'用户名或密码错误'];
                    }
    			}else{   				
    				$arr = ['code'=>0,'msg'=>'登陆失败'];
    			}
    		}else{
					//非法请求 404
    			$arr = ['code'=>2,'msg'=>'非法请求'];
    		}
    	}else{
    			//非法请求 404
    			$arr = ['code'=>2,'msg'=>'非法请求'];
    	}
    	return json($arr);
    }
    //企业用户登录
    public function companyLogin()
    {
    	if(Request::instance()->isPost()){
            $data = input('post.');
            if($this->redis->get('csrftoken')===$data['token']){
                //查询数据库
                $res = Db::name('company')->field('company_pwd,company_id')->where(["company_tel"=>$data['username'],'company_status'=>1])->find();
                if($res){
                    //查到了用户 比较密码
                    if (password_verify($data['pwd'],$res['company_pwd'])) { 
                        $arr = ['code'=>1,'msg'=>'登录成功'];
                        Session::set('tel',$data['username'].'公司');
                        Session::set('usercate',2);
                        Session::set('companytel',$data['username']);
                        Session::set('companyid',$res['company_id']);
                        if($data['save']=='save'){
                            Cookie::set('tel',$data['username'].'公司',['prefix'=>'job_','expire'=>3600*24*7]);
                        }
                        
                    } else{
                        $arr = ['code'=>0,'msg'=>'用户名或密码错误'];
                    }
                }else{                  
                    $arr = ['code'=>0,'msg'=>'登陆失败'];
                }
            }else{
                    //非法请求 404
                $arr = ['code'=>2,'msg'=>'非法请求'];
            }
        }else{
                //非法请求 404
                $arr = ['code'=>2,'msg'=>'非法请求'];
        }
        return json($arr);
    }

    public function qqLogin()
    {
        // 1. 获取code  code 只可以使用一次为了安全
        $code = $_GET['code'];

        // 2. 获取access_token
        $token_url = 'https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=101455707&client_secret=ea73ce932cdad0990366f751118199c2&code='.$code.'&state=test&redirect_uri=http://www.zzz.com/index/login/qqlogin';
        $token_res = https_request($token_url);

        // 切割str
        $access_token = substr($token_res,13,32);


        // 3. 获取openid
        $openid_url = 'https://graph.qq.com/oauth2.0/me?access_token='.$access_token;
        $openid_res  = https_request($openid_url);
        // var_dump($openid_res);die;

        // 解析openid res 数据

        $lpos = strpos($openid_res, "(");
        $rpos = strrpos($openid_res, ")");
        $openid_res  = substr($openid_res, $lpos + 1, $rpos - $lpos -1);
        $data = json_decode($openid_res,true);
        $openid = $data['openid'];

        // 4. 获取userinfo
        $user_url = 'https://graph.qq.com/user/get_user_info?access_token='.$access_token.'&oauth_consumer_key=101455707&openid='.$openid;
        $user_res = https_request($user_url);

        $userinfo = json_decode($user_res,true);
        // var_dump($userinfo);die;

        $row = Db::name('user')->field('user_tel')->where('user_openid',$openid)->find();
        if($row){
            //通过openid查询到了电话 登陆成功
            Session::set('tel',$row['user_tel'].'用户');
            Session::set('usercate',1);
               if (isMobile()) {
                     $this->redirect('index/phone/index');
               }else{
                     $this->redirect('index/index/index');

               }
        }else{
            //没查到 绑定电话  B5ECE76DE995B8F625C20F2032497219
            $this->redirect('index/login/telemail',array('openid'=>$openid));
        }
    }

    //邮箱找回密码(显示)
    public function forgetPwd()
    {
        return view('login/forgetpwd');
    }

    public function sendEmail()
    {
        if(request()->isPost()){
            $data = input('post.');
            if(!captcha_check($data['verifycode'])) {
                // 校验失败
                $result = ['code'=>'0','msg'=>'验证码不正确'];
                // $this->error('验证码不正确');
            }else{
                $this->phpEmail($data['email']);
                $result = ['code'=>1,"msg"=>'发送成功'];
            }
        }else{
             $result = ['code'=>'0','msg'=>'非法请求'];
        }

        return json($result);
    }


    public function phpEmail($email)
    {
        // require 'vendor/autoload.php';
        $mail = new PHPMailer(true);
        try {
            //Server settings
            $mail->SMTPDebug = 2;                                 // Enable verbose debug output
            $mail->isSMTP();                                      // Set mailer to use SMTP
            $mail->Host = 'smtp.aliyun.com';  // Specify main and backup SMTP servers
            $mail->SMTPAuth = true;                               // Enable SMTP authentication
            $mail->Username = 'zhangxuedong123@aliyun.com';                 // SMTP username
            $mail->Password = '739956552..0';                           // SMTP password
            $mail->CharSet = 'UTF-8';

            //Recipients
            $mail->setFrom('zhangxuedong123@aliyun.com', 'job兼职');
            $mail->addAddress($email, '');     // Add a recipient

            $row = Db::name('user')->field('user_id')->where('user_email',$email)->find();
            if($row){
                 $id = $row['user_id'];   
                //Content
                 $url = "http://www.zzz.com/resetpwd/{$id}";
            }else{
                 $url = "http://www.zzz.com/index/login/pwdreset";
            }
            $mail->isHTML(true);                                  // Set email format to HTML
            $mail->Subject = 'job兼职找回密码通知';
            $mail->Body    = "您好 {$email} <br>您已经请求了job兼职重置密码，可以点击下面的链接来重置密码。<b>{$url}</b>";
            $mail->send();
        } catch (Exception $e) {
        }
    }

    //显示重新输入密码页面 绑定邮箱
    public function passwordReset($id)
    {
        $this->assign('id',$id);
        return $this->fetch('login/changepwd');
    }


    //重置密码  有邮箱
    public function resetpwd()
    {
        $data = input('post.');
        $pwd = password_hash($data['pwd'],PASSWORD_DEFAULT);
        if(DB::name('user')->where('user_id',$data['id'])->update(["user_pwd"=>$pwd])){
            $result = ['code'=>1,"msg"=>'修改成功'];
        }else{
            $result = ['code'=>1,"msg"=>'修改失败,请稍后再试'];
        }
        return json($result);
    }

    //注册
    public function showReg()
    {
        return view('login/register');
    }

    //发送手机验证码
    public function sendAuth()
    {
        if(Request::instance()->isPost()){
            $data = input('post.');
            $tel = $data['username'];
            $str = '18241201411';    
            if(stristr($str,$tel)!==false){               
                    $num = mt_rand(100000, 999999);
                    Session::set('auth',$num);
                    $p = new SendMsg;
                    $p->sendTemplateSMS($tel, array($num, 9), 1);   
            }
        }
    }
        // 未绑定邮箱
    public function pwdReset()
    {
        return $this->fetch('login/changepwdnoemail');
    }

    public function repwd()
    {
        $data = input('post.');
        $pwd = password_hash($data['pwd'],PASSWORD_DEFAULT);
        // dump($data);
        if(DB::name('user')->where('user_tel',$data['tel'])->update(["user_pwd"=>$pwd])){
            $result = ['code'=>1,"msg"=>'修改成功'];
        }else{
            $result = ['code'=>1,"msg"=>'修改失败,请稍后再试'];
        }
        return json($result);
    }
    //企业用户未绑定邮箱手机修改密码
    public function companyresetpwd()
    {
        return view('login/companypwd');
    }
    // 修改
    public function companypwd()
    {
     if(Request::instance()->isPost()){
            $data = input('post.');
            $tel = $data['username'];
            $code = $data['auth'];
            $pwd = password_hash($data['pwd'],PASSWORD_DEFAULT);     
            if($code==Session::get('auth')){
                if(Db::name('company')->where('company_tel',$tel)->find()){
                     if(DB::name('company')->where('company_tel',$tel)->update(["company_pwd"=>$pwd])){
                        $result = ["code"=>1,"msg"=>"修改成功"];
                    }
                }else{
                    $result = ["code"=>0,"msg"=>"用户不存在请先注册"];
                }

            }else{
                $result = ["code"=>0,"msg"=>"验证码不正确"];
            }
        }

        return json($result);
    }
    public function regUser()
    {
        if(Request::instance()->isPost()){
            $data = input('post.');
            $tel = $data['username'];
            $code = $data['auth'];
            $pwd = password_hash($data['pwd'],PASSWORD_DEFAULT);     
            if($code==Session::get('auth')){
                // dump($data);die;
                if(DB::name('user')->where('user_tel',$tel)->find()){
                    $result = ["code"=>0,"msg"=>"该手机已注册"];
                }else{
                    $insert['user_tel'] = $tel;
                    $insert['user_pwd'] = $pwd;
                    $insert['user_regtime'] = time(); 
                    if($uid = Db::name('user')->insertGetId($insert)){
                            $regip = Request::instance()->ip();
                            $list = array(
                                "uid" => $uid,
                                "regip" => $regip
                            );
                            $ret = Db::name('usermore_information')->insertGetId($list);
                            if($ret){
                                $result = ["code"=>1,"msg"=>"注册成功"];
                            }
                    }else{
                        $result = ["code"=>0,"msg"=>"注册失败"];
                    }
                }
            }else{
                $result = ["code"=>0,"msg"=>"验证码不正确"];
            }
        }

        return json($result);
    }





    public function regCompany()
    {
        if(Request::instance()->isPost()){
            $data = input('post.');
            $tel = $data['username'];
            $code = $data['auth'];
            $pwd = password_hash($data['pwd'],PASSWORD_DEFAULT);     
            if($code==Session::get('auth')){
                // dump($data);die;
                if(DB::name('company')->where('company_tel',$tel)->find()){
                    $result = ["code"=>0,"msg"=>"该手机已注册"];
                }else{
                    $insert['company_tel'] = $tel;
                    $insert['company_pwd'] = $pwd;
                    $insert['company_regtime'] = time(); 
                    if(Db::name('company')->insert($insert)){
                        $result = ["code"=>1,"msg"=>"注册成功"];
                    }else{
                        $result = ["code"=>0,"msg"=>"注册失败"];
                    }
                }
            }else{
                $result = ["code"=>0,"msg"=>"验证码不正确"];
            }
        }
        return json($result);
    }
}